#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <time.h>
#include <iostream>

using namespace std;
using namespace cv;

void bright(Mat &input_img)
{
    cv::Mat gray_img;
    cv::cvtColor(input_img, gray_img, CV_BGR2GRAY);

    float cast = 1.0;
    float da = 0;
    float a = 0;
    float Ma = 0;
    int hist[256] = {0};

    for (int i = 0; i < gray_img.rows; i++)
    {
        for (int j = 0; j < gray_img.cols; j++)
        {
            a += float(gray_img.at<uchar>(i, j) - 128); // 在计算过程中，考虑128为亮度均值点
            hist[gray_img.at<uchar>(i, j)]++;
        }
    }

    da = a / float(gray_img.total());

    for (int i = 0; i < 256; i++)
    {
        Ma += abs(i - 128 - da) * hist[i];
    }

    Ma /= float(gray_img.total());
    cast = abs(da) / abs(Ma);
    printf("light: %f\n", cast);
    if (cast > 1)
    {
        if (da > 0)
            printf("light\n");
        else
            printf("dark\n");
    }
}

int main()
{
    //读入视频
    VideoCapture capture("/Users/lukeskywalker/Desktop/occlude.mov");
    //VideoCapture capture(0);
    //namedWindow("camera", WINDOW_AUTOSIZE);
    //namedWindow("moving area", WINDOW_AUTOSIZE);
    //获取整个帧数

    Mat frame;
    Mat gray;
    Mat tempframe;
    int framenum = 0;
    //读取一帧处理
    while (true)
    {
        if (!capture.isOpened())
        {
            cout << "read video failure" << endl;
            return -1;
        }
        //tempframe = capture.read(frame);

        //获取整个帧数
        long totalFrameNumber = capture.get(CV_CAP_PROP_FRAME_COUNT);
        //cout << "整个视频共" << totalFrameNumber << "帧" << endl;

        capture >> frame;
        tempframe = frame;
        framenum++;
        if (framenum == 1)
        {
            cvtColor(tempframe, gray, CV_BGR2GRAY);
        }
        if (framenum >= 2)
        {
            cvtColor(tempframe, gray, CV_BGR2GRAY); //转化为单通道灰度图，此时currentFrame已经存了tempFrame的内容

            //显示图像
            imshow("camera", tempframe);
            imshow("moving area", gray);
        }

        if (!(framenum % 1))
        {
            printf("f:%d\n", framenum);
            //***suanfa;
        }
        bright(frame);
        //把当前帧保存作为下一次处理的前一帧
        waitKey(33);
    } //end while
}